﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Publishing.WebControls;
using System.Collections;

namespace SP2010.Enhancements.Management
{
    public class Tools
    { 
        /// <summary>
        /// Updates a document on a SharePoint Application List
        /// </summary>
        public void UpdateDocumentOnSPList(string rootSiteURL, string listRelativeUrl, string fileName, string newContent)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite siteColl = new SPSite(rootSiteURL))
                {
                    using (SPWeb web = siteColl.OpenWeb())
                    {
                        string url = rootSiteURL + listRelativeUrl + fileName;
                        SPFile spfile = web.GetFile(url);
                        if (spfile.Exists)
                        {
                            byte[] byteArrayFileContentsBefore = spfile.OpenBinary();

                            if (byteArrayFileContentsBefore.Length > 0)
                            {
                                byte[] byteArrayFileContentsAfter = null;
                                byteArrayFileContentsAfter = enc.GetBytes(newContent);
                                spfile.SaveBinary(byteArrayFileContentsAfter); //save to the file.                                    
                            }
                        }
                        else
                        {
                            createDocumentOnSPList(rootSiteURL, listRelativeUrl, fileName, newContent);
                        }
                    }
                }
            });
        }

        /// <summary>
        /// Creates a document on a SharePoint Application List
        /// </summary>
        public void createDocumentOnSPList(string rootSiteURL, string listRelativeUrl, string fileName, string content)
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite siteColl = new SPSite(rootSiteURL))
                {
                    using (SPWeb web = siteColl.OpenWeb())
                    {
                        string url = rootSiteURL + listRelativeUrl + fileName;
                        SPFile spfile = web.GetFile(url);
                        if (!spfile.Exists)
                        {
                            byte[] byteArray = enc.GetBytes(content);
                            web.Files.Add(url, byteArray);
                        }
                    }
                }
            });
        }

        /// <summary>
        /// Converts an absolute URL to a relative url
        /// </summary>
        public string getRelativeURL(string absoluteURL, string baseSiteURL)
        {
            string relativeURL = absoluteURL.Replace(baseSiteURL, "").Trim();
            if (relativeURL == "") relativeURL = "/";
            return relativeURL;
        }

        /// <summary>
        /// Converts an relative URL to an absolute url
        /// </summary>
        public string getAbsoluteURL(string relativeURL, string baseSiteURL)
        {
            return baseSiteURL + relativeURL;
        }

        /// <summary>
        /// Gets the URL (i = 0) or description (i = 1) component from a Link type field
        /// </summary>
        public string getLinkFieldTypeComponents(string link, int i)
        {
            if (link.Contains(Constants.LINK_FIELD_SEP_OP))
                return link.Split(Constants.LINK_FIELD_SEP_OP)[i].ToString();
            else return link;
        }

        /// <summary>
        ///Get the corresponding site URL ID
        /// </summary>
        public string getSiteID(string _appURL)
        {
            string id = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(_appURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        id = web.ID.ToString();
                    }
                }
            });
            return id;
        }

        /// <summary>
        ///Activate or deactivate the SPSite feature 
        /// </summary>
        public void activateDeactivateSiteFeature(SPSite site, Guid featureID, bool isActivate)
        {
            site.AllowUnsafeUpdates = true;
            SPFeature spFeature = site.Features[featureID];
            if (isActivate)
            {
                if (spFeature == null)
                    site.Features.Add(featureID);
            }
            else
            {
                if (spFeature != null)
                    site.Features.Remove(featureID);
            }
            site.AllowUnsafeUpdates = true;

        }

        /// <summary>
        ///Activate or deactivate the SPWeb feature 
        /// </summary>
        public void activateDeactivateWebFeature(SPWeb web, Guid featureID, bool isActivate)
        {
            web.AllowUnsafeUpdates = true;
            SPFeature spFeature = web.Features[featureID];
            if (isActivate)
            {
                if (spFeature == null)
                    web.Features.Add(featureID);
            }
            else
            {
                if (spFeature != null)
                    web.Features.Remove(featureID);
            }
            web.AllowUnsafeUpdates = false;
        }

        /// <summary>
        /// Returns true if the corresponding ID feature is activated. Else returns false.
        /// </summary>        
        public bool featureActivatedFirstLevelSPWeb(SPWeb Web, Guid id)
        {
            Tools Tls = new Tools();
            SPWeb flWeb = Tls.getFirstLevelSPWeb(Web);
            SPFeatureManager spFeatMngr = new SPFeatureManager();
            return spFeatMngr.matchFeature(flWeb.Features, id);
        }

        /// <summary>
        ///Converts string to GUID 
        /// </summary>
        public Guid getGUID(string guid)
        {
            return new Guid(guid);
        }

        /// <summary>
        ///This method returns a URI object based n a URL 
        /// </summary>
        public Uri getURI(string absoluteUrl)
        {
            return new Uri(absoluteUrl);
        }

        /// <summary>
        ///This method changes the masterpage of a SPWeb 
        /// </summary>
        public void changeSPWebMasterpage(SPWeb Web, string absoluteUrl)
        {
            Web.AllowUnsafeUpdates = true;
            Web.CustomMasterUrl = absoluteUrl;
            Web.Update();
            Web.AllowUnsafeUpdates = false;
        }

        /// <summary>
        ///This method redirects to the specified URL 
        /// </summary>
        public void redirectToPage(string URL)
        {
            SPUtility.Redirect(URL, SPRedirectFlags.Trusted, HttpContext.Current);
        }

        /// <summary>
        ///This method returns the corresponding SPWeb depth regarding the root. If undefined, returns -1.
        /// </summary>
        public int getSPWebDepth(SPWeb currentWeb)
        {
            int depth = -1;
            if (!currentWeb.IsRootWeb)
            {
                depth = 0;
                do //RUN PARENTS:
                {
                    depth++;
                    currentWeb = currentWeb.ParentWeb;
                }
                while (!currentWeb.IsRootWeb);
            }
            else return 0;
            return depth;
        }

        /// <summary>
        ///This method returns the first level SPWeb.
        /// </summary>
        public SPWeb getFirstLevelSPWeb(SPWeb currentWeb)
        {
            if (!currentWeb.IsRootWeb)
            {
                Boolean exit = false;
                do
                {
                    if (currentWeb.ParentWeb.IsRootWeb) exit = true;
                    else currentWeb = currentWeb.ParentWeb;
                }
                while (!exit);
                return currentWeb;
            }
            else return null;
        }

        /// <summary>
        ///This method checks the access level a user has on a SPWeb based on the login. If undefined returns false.
        /// </summary>
        public bool checkLoginAccessOnSPweb(SPWeb Web, string login, SPBasePermissions permissions)
        {
            bool access = false;
            try
            {
                SPContext.Current.Site.CatchAccessDeniedException = false;
                access = Web.DoesUserHavePermissions(login, permissions);
                return access;
            }
            catch
            {
                access = false;
                return access;
            }
        }

        /// <summary>
        ///This method returns a SPWeb based un the URL. If undefined returns NULL.
        /// </summary>
        public SPWeb getSPWeb(string webUrl)
        {
            return new SPSite(webUrl).OpenWeb();
        }

        /// <summary>
        ///It returns the SPField value of a Publishing page
        /// </summary>
        public string getPageLayoutFieldContent(PublishingPage ppPage, string StaticName)
        {
            try
            {
                switch (StaticName)
                {

                    case Constants.SN_SP2010_TITLE:
                        return ppPage.Title;
                    
                    default:
                        return ppPage.ListItem.Properties[StaticName].ToString();
                }
            }
            catch 
            {
                throw;
            }
        }

        /// <summary>
        ///Log errors in portal.
        /// </summary>
        public void logErrors(string errorCategory, Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(errorCategory, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
        }

        /// <summary>
        ///Returns the HTML IMG tag's source.
        /// </summary>
        public string getImageTagSrc(string tag)
        {
            string src = string.Empty;
            try
            {
                if(tag.Trim().Length > 0)
                {
                    string srcAtr = string.Empty;
                    tag = tag.ToLower().Trim();
                    char[] tagDelimiter = new char [] { Constants.HTML_TAG_DELIMITER };
                    char[] atrbDelimiter = new char [] { Constants.HTML_ATRB_DELIMITER };
                    string[] sArr = tag.Split(tagDelimiter);
                    foreach (string s in sArr) if (s.Contains("src")) srcAtr = s;
                    src = srcAtr.Split(atrbDelimiter)[1];
                }
            }
            catch
            {
                throw;
            }  
            return src;
        }

        /// <summary>
        ///Removes the HTML tag's from source.
        /// </summary>
        public string removeHTMLtags(string source)
        {
            try
            {
                return HTMLManager.StripTagsCharArray(source);
            }
            catch
            {
                throw;
            }  
        }
    }
}
